/**
 * Created by Administrator on 2017/3/21.
 */
import React, {Component} from 'react';
import {
  Form,
  Button,
  Badge,
  Select,
  DatePicker,
  Radio,
  Descriptions,
  Input,
  Upload,
  Icon,
  TreeSelect,
  InputNumber,
} from 'antd';
import {connect} from 'dva';
import moment from 'moment'
import request from '@/utils/request';
import config from '@/config/config'
const { TextArea } = Input;
const { Option } = Select;
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const ButtonGroup = Button.Group;
let uuid = 2;
class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meterArr: [1, 2],
      meterActiveKey: ['1', '2'],
      meter1: [],
      meter2: [],
      fileList:this.props.editRecord?this.props.editRecord.attachments.map((item,index)=>{
        return {
          uid: item.key,
          name: item.name,
          status: 'done',
          url: `${config.prefix}/reimbursement_lists/${this.props.editRecord.id}/attachments/${this.props.editRecord.attachments[index].key}/download??token=Bearer ${sessionStorage.getItem('token')}`,
        }
      }):[],
      all_staffs:[],
      all_users_reviewer:[],
      all_users_rehearer:[],
      all_departments:[],
      format:'YYYY-MM-DD'
    };
  }
  componentDidMount() {
    const that=this;
    this.fetAllUser()
    this.fetAllUser('all_users_reviewer')
    this.fetAllUser('all_users_rehearer')
    request(`/all_departments`, {
      method: 'GET',
    }).then((response)=> {
      console.log('all_structures', response)
      if(response.status===200){
        that.setState({
          all_departments:response.data.data
        })
      }
    })
    if(this.props.editRecord){
      uuid=this.props.editRecord.reimbursement_list_items.length
      this.setState({
        meterArr:this.props.editRecord.reimbursement_list_items.map((item,index)=>{
          return index+1
        }),
        meterActiveKey:this.props.editRecord.reimbursement_list_items.map((item,index)=>{
          return (index+1).toString()
        }),
      })
      for(let i=0;i<this.props.editRecord.reimbursement_list_items.length;i++){
        this.setState({
          [`meter${i+1}`]:[]
        },function() {
          that.props.form.setFieldsValue({
            [`name-${i+1}`]:this.props.editRecord.reimbursement_list_items[i].name,
            [`count-${i+1}`]:this.props.editRecord.reimbursement_list_items[i].count,
            [`price-${i+1}`]:this.props.editRecord.reimbursement_list_items[i].price,
            [`remark-${i+1}`]:this.props.editRecord.reimbursement_list_items[i].remark,
          })
        })
      }
    }

  }

  fetAllUser=(type,value)=>{
    const that=this;
    request(`/all_staffs`, {
      method: 'GET',
      params:{
        department_id:value?value:''
      }
    }).then((response)=> {
      console.log('all_structures', response)
      if(response.status===200){
        if(type){
          that.setState({
            [type]:response.data.data
          })
        }else{
          that.setState({
            all_staffs:response.data.data
          })
        }

      }
    })
  }
  addMeter = () => {
    uuid++;
    this.state.meterArr.push(uuid);
    this.state.meterActiveKey.push(uuid.toString());
    this.setState({
      [`meter${uuid}`]: [],
      meterArr: this.state.meterArr,
      meterActiveKey: this.state.meterActiveKey,
    });
  };
  deleteMeter = (item) => {
    console.log('删除的item', item);
    if (this.state.meterArr.length === 1) {
      console.log('只有一个水表');
      // message.error('至少需要一个水表')
      // return false
    }
    const index = this.state.meterArr.indexOf(item);
    console.log('index', index);
    this.state.meterArr.splice(index, 1);
    this.setState({
      meterArr: this.state.meterArr,
    });
  };
  render() {
    const {getFieldDecorator} = this.props.form;
    const props = {
      onRemove: (file) => {
        this.setState(({ fileList }) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({ fileList }) => ({
          fileList: [...fileList,file],
        }));
        return false;
      },
      fileList: this.state.fileList,
    };
    const meterForms = this.state.meterArr.map((item, index) => {
      return (
        <Form style={{ display: 'flex' }} className={'custom-table-form'} key={index} layout="inline">
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`name-${item}`, {
              initialValue: '',
            })(
              <Input style={{  fontWeight: 'bold' }}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`price-${item}`, {
              initialValue: '',
            })(
              <Input style={{  fontWeight: 'bold' }}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`count-${item}`, {
              initialValue: '',
            })(
              <Input style={{  fontWeight: 'bold' }}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`remark-${item}`, {
              initialValue: '',
            })(
              <Input style={{  fontWeight: 'bold' }}/>,
            )}
          </FormItem>
          <div style={{ width: '80px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            <Button
              style={{ height: '22px' }}
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                e.stopPropagation();
                this.deleteMeter(item);
              }
              }
            >删除
            </Button>
          </div>


        </Form>
      );
    });
    return (
      <div>
        <Form>
          <Descriptions column={4} className={'blue-descriptions'}  title={<div style={{textAlign:'center'}}>报销详情</div>} bordered>
            <Descriptions.Item label="申请人"  span={2}>
              {sessionStorage.getItem('username')}
            </Descriptions.Item>
            <Descriptions.Item label="报销人"  span={2}>
              {getFieldDecorator('reimburser_id', {
                initialValue: this.props.editRecord?
                  `${this.props.editRecord.reimburser.id}#${this.props.editRecord.reimburser.name}`
                  :`${sessionStorage.getItem('user_id')}#${sessionStorage.getItem('username')}`,
              })(
                <Select   showSearch>
                  {
                    this.state.all_staffs.map((item,index)=>{
                      return <Option key={index} value={`${item.id}#${item.name}`}>
                        {item.name}
                      </Option>
                    })
                  }
                </Select>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="报销金额" span={4}>
              {getFieldDecorator('amount', {
                initialValue:this.props.editRecord?this.props.editRecord.amount:'',
              })(
                <InputNumber style={{width:'100%'}}/>
              )}

            </Descriptions.Item>
            <Descriptions.Item label="报销类型" span={4}>
              {getFieldDecorator('type', {
                initialValue:this.props.editRecord?this.props.editRecord.type:'',
              })(
                <TextArea rows={2}/>
              )}

            </Descriptions.Item>
            <Descriptions.Item label="报销事由" span={4}>
              {getFieldDecorator('cause', {
                initialValue:this.props.editRecord?this.props.editRecord.cause:'',
              })(
                <TextArea rows={3}/>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="报销项目" span={4}>
              <div style={{ border: '1px solid #d9d9d9', marginTop: '10px' }}>

                <div style={{
                  display: 'flex',
                  fontWeight: 'bold',
                  lineHeight: '32px',
                  height: '32px',
                  background: 'rgb(249,249,249)',
                }}>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>项目名称</div>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9', }}>单价</div>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>数量</div>
                  <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>备注</div>
                  <div style={{ width: '80px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>操作</div>
                </div>
                {meterForms}
                <Button type={'primary'} className={'btn-cyan'} icon={'plus'} block onClick={this.addMeter}>添加行</Button>

              </div>
            </Descriptions.Item>


            <Descriptions.Item label="上传附件" span={4}>
              {getFieldDecorator('file', {
                rules: [{required: true, message: '文件不能为空'}],
              })(
                <Upload.Dragger {...props}>
                  <p className="ant-upload-text" style={{fontSize:'14px'}}> <Icon type="inbox" />点击选择文件</p>
                </Upload.Dragger>
              )}

            </Descriptions.Item>
            <Descriptions.Item label="审批人" span={4}>
              {getFieldDecorator('reviewer_ids', {
                initialValue: this.props.editRecord?this.props.editRecord.reviewers.map((item,index)=>{
                  return {
                    key:`${item.user_id}#${item.name}`,
                    label:item.name
                  }
                }):[],
              })(
                <Select labelInValue={true} mode="multiple" showSearch>
                  {
                    this.state.all_users_reviewer.map((item,index)=>{
                      return <Option key={index} value={`${item.id}#${item.name}`}>
                        {item.name}
                      </Option>
                    })
                  }
                </Select>
              )}
            </Descriptions.Item>
            <Descriptions.Item label="抄送给" span={4}>
              {getFieldDecorator('replicator_ids', {
                initialValue: this.props.editRecord?this.props.editRecord.replicators.map((item,index)=>{
                  return {
                    key:`${item.user_id}#${item.name}`,
                    label:item.name
                  }
                }):[],
              })(
                <Select  labelInValue={true} mode="multiple" showSearch>
                  {
                    this.state.all_users_rehearer.map((item,index)=>{
                      return <Option key={index} value={`${item.id}#${item.name}`}>
                        {item.name}
                      </Option>
                    })
                  }
                </Select>
              )}
            </Descriptions.Item>
          </Descriptions>
        </Form>

      </div>
    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


